package com.hzw.net.manager

import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkRequest
import com.hzw.core.log.logE
import com.hzw.core.log.logI
import com.hzw.core.services.connectivityManager

/**
 *
 * @Author:         HuaZhongWei
 * @CreateDate:     2020/8/28 15:50
 *
 * @Description:    网络状态监听
 *
 */
object NetChangeManager {

    private var callback: ConnectivityManager.NetworkCallback? = null

    fun register(listener: OnNetChangedListener) {
        val request = NetworkRequest.Builder().build()
        callback = object : ConnectivityManager.NetworkCallback() {

            override fun onAvailable(network: Network) {
                "网络连接了  onAvailable ".logI()
                listener.onConnected(network)
            }

            override fun onLost(network: Network) {
                super.onLost(network)
                "网络不可用  onLost".logE()
                listener.onDisconnected()
            }
        }
        connectivityManager.registerNetworkCallback(request, callback!!)
    }

    fun unregister() {
        callback?.let {
            connectivityManager.unregisterNetworkCallback(it)
        }
    }
}

interface OnNetChangedListener {
    fun onDisconnected()
    fun onConnected(network: Network)
}